import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import GatherAdjustmentProcess from '@main/entities/service/admin/gather/gather-adjustment-process.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
@Injectable()
export class GatherAdjustmentProcessService {
  constructor(
    @InjectRepository(GatherAdjustmentProcess)
    private adjustmentProcessRepository: Repository<GatherAdjustmentProcess>
  ) {}

  async list() {
    return await this.adjustmentProcessRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { adjustmentProcessName, adjustmentProcessCode } = entity;

    return await this.adjustmentProcessRepository.findAndCount({
      where: {
        adjustmentProcessCode: Like(`%${adjustmentProcessCode}%`),
        adjustmentProcessName: Like(`%${adjustmentProcessName}%`),
      },
      order: {
        id: 'ASC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user) {
    await this.adjustmentProcessRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
  }

  /**
   * 更新
   */
  async update(data, user) {
    const { id, remark, adjustmentProcessName, adjustmentBtn, adjustmentInterface } = data;

    await this.adjustmentProcessRepository.update(
      { id },
      {
        adjustmentProcessName,
        adjustmentBtn,
        adjustmentInterface,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );
  }

  /**
   * 删除
   */
  async delete(idList) {
    await this.adjustmentProcessRepository.delete(idList);
  }

  async isExistKey(data) {
    const { adjustmentProcessCode } = data;

    const result = await this.adjustmentProcessRepository.findOne({
      where: { adjustmentProcessCode },
    });

    if (result) throw new ApiException(10044);
  }
}
